mod application_handler;
mod config;
mod model;

use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};

use tokio::sync::Mutex;

pub use application_handler::*;
pub use model::local::ollama;

use model_graph_types::application::ApplicationHandler;

lazy_static::lazy_static! {
    //
    pub(crate) static ref APPLICATION_HANDLERS: RwLock<HashMap<String, Arc<Mutex<SimpleApplicationHandler>>>> =
        RwLock::new(HashMap::new());

}

pub async fn get_application_handler(
    application_identifier: &String,
    is_installed: bool,
) -> anyhow::Result<Arc<Mutex<dyn ApplicationHandler + Send>>> {
    //
    let exist = {
        let cache = APPLICATION_HANDLERS
            .read()
            .map_err(|err| anyhow::anyhow!("{}", err))?;
        cache.contains_key(&application_identifier.to_lowercase())
    };
    if exist {
        if let Some(arc_handler) = APPLICATION_HANDLERS
            .read()
            .map_err(|err| anyhow::anyhow!("{}", err))?
            .get(&application_identifier.to_lowercase())
        {
            //
            let arc_handler = arc_handler.clone();
            Ok(arc_handler)
        } else {
            Err(anyhow::anyhow!("存在但获取错误:{}", application_identifier))
        }
    } else {
        //创建
        let new_handler =
            SimpleApplicationHandler::new(application_identifier, is_installed).await?;
        let arc_handler = Arc::new(Mutex::new(new_handler));
        //
        let cache_result = APPLICATION_HANDLERS
            .write()
            .map_err(|err| anyhow::anyhow!("获取锁失败:{}", err));

        match cache_result {
            Ok(mut cache) => {
                cache.insert(application_identifier.to_lowercase(), arc_handler.clone());
                tracing::debug!("添加成功!");
                Ok(arc_handler)
            }
            Err(err) => Err(anyhow::anyhow!("{}", err)),
        }
    }
}

pub async fn remove_application_handler(application_identifier: &String) -> anyhow::Result<()> {
    //
    let exist = {
        let cache = APPLICATION_HANDLERS
            .read()
            .map_err(|err| anyhow::anyhow!("{}", err))?;
        cache.contains_key(&application_identifier.to_lowercase())
    };
    if exist {
        let cache_result = APPLICATION_HANDLERS
            .write()
            .map_err(|err| anyhow::anyhow!("获取锁失败:{}", err));

        match cache_result {
            Ok(mut cache) => {
                cache.remove(&application_identifier.to_lowercase());
                tracing::debug!("移除成功!");
                Ok(())
            }
            Err(err) => {
                tracing::debug!("移除失敗!{}", err);
                Ok(())
            }
        }
    } else {
        Ok(())
    }
}
